package com.hmall.gateway.filer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.AntPathMatcher;
import com.hmall.common.exception.UnauthorizedException;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.util.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@RequiredArgsConstructor
public class PrintAnyGlobalFilter implements GlobalFilter, Ordered {
    private final JwtTool jwtTool;
    private final AuthProperties authProperties;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       /* //编写过滤器逻辑
        System.out.println("未登录，无法访问");
        //放行
        return chain.filter(exchange);
        //拦截
        ServerHttpResponse response = exchange.getResponse();
        response.setRawStatusCode(401);
        return response.setComplete();*/
        //1. 获取请求头
        ServerHttpRequest request = exchange.getRequest();
        //2.判断是否不需要拦截
       if(isExclude( request.getPath().toString())){
           //无需拦截 放行
           return chain.filter(exchange);
       }
       //3.获取请求头
        String token = null;
        List<String> headers = request.getHeaders().get("authorization");
       if(!CollUtil.isEmpty(headers)){
           token = headers.get(0);
       }
       //4.解析校验 token
        Long userId = null;
       try {
           userId = jwtTool.parseToken(token);
       } catch (UnauthorizedException e) {
           //token无效  拦截
           ServerHttpResponse response = exchange.getResponse();
           response.setRawStatusCode(401);
           return response.setComplete();
       }
       // 如果有效传递用户信息、
        System.out.println("用户id：" + userId);
        String userInfo = userId.toString();
        ServerWebExchange ex = exchange.mutate()
                .request(b -> b.header("user-info", userInfo))
                .build();

        //放行
        return chain.filter(ex);
    }

    private boolean isExclude(String antPath) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if(antPathMatcher.match(pathPattern, antPath)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

